//
//  NetworkTools+OAuth.swift
//  1.新浪微博
//
//  Created by 温泉 on 16/3/5.
//  Copyright © 2016年 itcast. All rights reserved.
//

import Foundation
// 网络工具 - 身份授权部分

extension NetworkTools {
    
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }
    
    func loadAccessToken(code: String, finished: ([String:
        AnyObject]?)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appkey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
            request(.POST, URLString: urlString, parameters: params) {[weak self] result in
                
                // result 是 token 的结果字典，是可选的！
                // 如果要使用 key 从字典中取值，必须保证字典存在
                guard let result = result,
                    let access_token = result["access_token"] as? String,
                    let uid = result["uid"] as? String else {
                        
                        print("数据格式不正确")
                        
                        // 一定要完成回调，通知调用方请求失败
                        finished(nil)
                        return
                }
                
                // 继续加载用户数据
                self?.loadUser(access_token, uid: uid, finished: { (userDict) -> () in
                    // 合并字典
                    // 1> 判断用户字典是否有值
                    guard var userDict = userDict else {
                        print("用户数据加载错误")
                        
                        finished(nil)
                        return
                    }
                    
                    // 2> 合并字典
                    for (k, v) in result {
                        userDict[k] = v
                    }
                    
                    // 3> 完成回调
                    finished(userDict)
                })
            }
    }
}

    
